﻿using UnityEngine;
using System.Collections;

public class SheepPather : MonoBehaviour {

	public Vector2 finalGoal;
	public bool	hasGoal;
	public NavMesh navMesh;

	public float randomRadius = 4.0f;

	public float movementForceMagnitude = 10.0f;


	// Use this for initialization
	void Start () {
		NoCake (transform.position);
	}

	void Update() {


	}

	public void ThereIsCake ( Vector2 cakePos )
	{
		finalGoal = cakePos;
		hasGoal = true;
	}

	public void NoCake ( Vector2 cakePos )
	{
		finalGoal = cakePos + Random.insideUnitCircle * randomRadius;
		hasGoal = true;
	}

	void FixedUpdate () {
		if (hasGoal) 
		{
			NavMeshPath path = new NavMeshPath();
			NavMesh.CalculatePath(transform.position, ToVector3(finalGoal), -1, path);

			if( path.status != NavMeshPathStatus.PathInvalid )
			{
				if(path.corners.Length > 1 )
				{
					Vector3 corner = path.corners[1];
					Vector2 nextGoal = ToVector2( corner );
					Vector2 position = ToVector2( this.transform.position );

					Vector2 diff = nextGoal - position;


					if (diff.magnitude > 0.01f)
					{
						diff.Normalize ();
						Vector3 force = ToVector3(diff);
						rigidbody.AddForce (force * movementForceMagnitude);
					}
						


				}
			}
		}


	}


	Vector3 ToVector3( Vector2 position ) 
	{
		return new Vector3 (position.x, 0, position.y);
	}


	Vector2 ToVector2( Vector3 position ) 
	{
		return new Vector2 (position.x, position.z);
	}


}
